<template>
  <div v-if="showPlayer" class="spotify-player">
    <!-- 隐藏的音频元素 -->
    <audio
      ref="audio"
      @loadstart="onLoadStart"
      @loadedmetadata="onLoadedMetadata"
      @canplay="onCanPlay"
      @timeupdate="onTimeUpdate"
      @play="onPlay"
      @pause="onPause"
      @ended="onEnded"
      @waiting="onWaiting"
      @stalled="onStalled"
      @error="onError"
      style="display: none;"
      preload="metadata"
      :muted="false"
      :autoplay="false"
      :loop="false"
      :controls="false">
    </audio>

    <div class="player-container">
      <!-- 左侧：当前播放信息 -->
      <div class="now-playing">
        <div class="track-info">
          <div class="track-image"  v-if="currentMusic">
          <img v-if="currentMusic?.coverPath" :src="getCoverUrl(currentMusic.coverPath)" :alt="currentMusic.title">
            <div v-else class="default-cover">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                <path d="12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z"/>
              </svg>
        </div>
          </div>
          <div class="track-details"  v-if="currentMusic">
            <div class="track-name">{{ currentMusic?.title || '选择音乐' }}</div>
            <div class="track-artist">
              {{ currentMusic?.artist || '开始播放' }}
              <span v-if="currentMusic && isExternalMusic" class="external-badge">🌐</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 中央：播放控制 -->
      <div class="player-controls">
        <div class="control-buttons">
          <button 
            class="control-btn shuffle-btn" 
            @click="toggleShuffle"
            :class="{ 'active': isShuffle }"
            title="开启随机播放">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M13.151.922a.75.75 0 1 0-1.06 1.06L13.109 3H11.16a3.75 3.75 0 0 0-2.873 1.34l-6.173 7.356A2.25 2.25 0 0 1 .39 12.5H0V14h.391a3.75 3.75 0 0 0 2.873-1.34l6.173-7.356a2.25 2.25 0 0 1 1.724-.804h1.947l-1.017 1.018a.75.75 0 0 0 1.06 1.06L15.98 3.75 13.151.922zM.391 3.5H0V2h.391c1.109 0 2.16.49 2.873 1.34L4.89 5.277l-.979 1.167L1.265 4.84A2.25 2.25 0 0 0 .39 3.5z"/>
              <path d="m7.5 10.723.98-1.167.957 1.14a2.25 2.25 0 0 0 1.724.804h1.947l-1.017-1.018a.75.75 0 1 1 1.06-1.06l2.829 2.828-2.829 2.828a.75.75 0 1 1-1.06-1.06L13.109 13H11.16a3.75 3.75 0 0 1-2.873-1.34l-.787-.938z"/>
            </svg>
          </button>

          <button 
            class="control-btn" 
            @click="previous" 
            :disabled="!hasPrevious"
            title="上一曲">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M3.3 1a.7.7 0 0 1 .7.7v5.15l9.95-5.744a.7.7 0 0 1 1.05.606v12.588a.7.7 0 0 1-1.05.606L4 8.149V13.3a.7.7 0 0 1-1.4 0V1.7a.7.7 0 0 1 .7-.7z"/>
            </svg>
          </button>

          <button 
            class="play-pause-btn" 
            @click="handlePlayClick" 
            :disabled="isLoading"
            title="播放/暂停">
            <div v-if="isLoading" class="loading-spinner">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" opacity="0.3"/>
                <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </div>
            <svg v-else-if="isPlaying" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M8 5v14l11-7z"/>
            </svg>
          </button>

          <button 
            class="control-btn" 
            @click="next" 
            :disabled="!hasNext"
            title="下一曲">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M12.7 1a.7.7 0 0 0-.7.7v4.45L3.05 1.02A.7.7 0 0 0 2 1.63v11.76a.7.7 0 0 0 1.05.61L12 8.85v4.45a.7.7 0 0 0 1.4 0V1.7a.7.7 0 0 0-.7-.7z"/>
            </svg>
          </button>

          <button 
            class="control-btn repeat-btn" 
            @click="toggleRepeat"
            :class="{ 'active': playMode !== 'normal' }"
            :title="getRepeatTitle">
            <svg v-if="playMode === 'repeat-one'" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
              <path d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
              <text x="8" y="10.5" text-anchor="middle" font-size="5" fill="currentColor" font-weight="bold">1</text>
            </svg>
            <svg v-else width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
              <path d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
            </svg>
          </button>
        </div>
        
        <!-- 进度条 -->
        <div class="progress-section">
          <span class="time-display">{{ formattedCurrentTime }}</span>
          <div 
            class="progress-bar-container" 
               @mousedown="onProgressMouseDown"
            @mousemove="onProgressMouseMove"
            @mouseleave="hideProgressTooltip"
            ref="progressContainer">
            <div class="progress-bar">
            <div class="progress-background"></div>
            <div class="progress-fill" :style="{ width: progress + '%' }"></div>
              <div 
                class="progress-handle" 
                :style="{ left: progress + '%' }"
                :class="{ 'dragging': isDragging }"></div>
          </div>
            <div 
              v-if="showProgressTooltip" 
              class="progress-tooltip" 
              :style="{ left: tooltipPosition + 'px' }">
              {{ tooltipTime }}
            </div>
          </div>
          <span class="time-display">{{ formattedDuration }}</span>
        </div>
      </div>

      <!-- 右侧：其他控制 -->
      <div class="extra-controls">
                  <button 
            class="control-btn heart-btn" 
            @click="handleToggleFavorite" 
            :disabled="!currentMusic"
            :class="{ 'active': isCurrentMusicFavorited }"
            title="添加到喜欢的音乐">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
            </svg>
        </button>

        <div class="volume-controls">
          <button class="control-btn volume-btn" @click="toggleMute" title="静音">
            <svg v-if="isMuted || volume === 0" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M6.717 3.55A.5.5 0 0 1 7 4v8a.5.5 0 0 1-.812.39L3.825 10.5H1.5A.5.5 0 0 1 1 10V6a.5.5 0 0 1 .5-.5h2.325l2.363-1.89a.5.5 0 0 1 .529-.06zM9.146 5.146a.5.5 0 0 1 .708 0L11 6.293l1.146-1.147a.5.5 0 1 1 .708.708L11.707 7l1.147 1.146a.5.5 0 0 1-.708.708L11 7.707 9.854 8.854a.5.5 0 1 1-.708-.708L10.293 7 9.146 5.854a.5.5 0 0 1 0-.708z"/>
            </svg>
            <svg v-else-if="volume < 0.33" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M6.717 3.55A.5.5 0 0 1 7 4v8a.5.5 0 0 1-.812.39L3.825 10.5H1.5A.5.5 0 0 1 1 10V6a.5.5 0 0 1 .5-.5h2.325l2.363-1.89a.5.5 0 0 1 .529-.06z"/>
              <path d="M9.025 8.25a2.25 2.25 0 0 1-.707 1.596l-.707-.708A1.25 1.25 0 0 0 8.025 8.25a1.25 1.25 0 0 0-.414-.892l.707-.708A2.25 2.25 0 0 1 9.025 8.25z"/>
            </svg>
            <svg v-else-if="volume < 0.66" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M6.717 3.55A.5.5 0 0 1 7 4v8a.5.5 0 0 1-.812.39L3.825 10.5H1.5A.5.5 0 0 1 1 10V6a.5.5 0 0 1 .5-.5h2.325l2.363-1.89a.5.5 0 0 1 .529-.06z"/>
              <path d="M9.025 8.25a2.25 2.25 0 0 1-.707 1.596l-.707-.708A1.25 1.25 0 0 0 8.025 8.25a1.25 1.25 0 0 0-.414-.892l.707-.708A2.25 2.25 0 0 1 9.025 8.25z"/>
              <path d="M10.121 12.596A6.48 6.48 0 0 0 12.025 8a6.48 6.48 0 0 0-1.904-4.596l-.707.707A5.48 5.48 0 0 1 11.025 8a5.48 5.48 0 0 1-1.61 3.89l.706.706z"/>
            </svg>
            <svg v-else width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M11.536 14.01A8.473 8.473 0 0 0 14.026 8a8.473 8.473 0 0 0-2.49-6.01l-.708.707A7.476 7.476 0 0 1 13.025 8c0 2.071-.84 3.946-2.197 5.303l.708.707z"/>
              <path d="M10.121 12.596A6.48 6.48 0 0 0 12.025 8a6.48 6.48 0 0 0-1.904-4.596l-.707.707A5.48 5.48 0 0 1 11.025 8a5.48 5.48 0 0 1-1.61 3.89l.706.706z"/>
              <path d="M10.025 8.75a3.5 3.5 0 0 1-1.318 2.75l-.707-.707A2.5 2.5 0 0 0 9.025 8.5a2.5 2.5 0 0 0-1.025-2.043l.707-.707A3.5 3.5 0 0 1 10.025 8.75z"/>
              <path d="M6.717 3.55A.5.5 0 0 1 7 4v8a.5.5 0 0 1-.812.39L3.825 10.5H1.5A.5.5 0 0 1 1 10V6a.5.5 0 0 1 .5-.5h2.325l2.363-1.89a.5.5 0 0 1 .529-.06z"/>
            </svg>
          </button>
          <div 
            class="volume-bar-container" 
            @mousedown="onVolumeMouseDown"
            @mousemove="onVolumeMouseMove"
            @mouseleave="hideVolumeTooltip"
            ref="volumeContainer">
            <div class="volume-bar">
          <div class="volume-background"></div>
          <div class="volume-fill" :style="{ width: (isMuted ? 0 : volume * 100) + '%' }"></div>
              <div 
                class="volume-handle" 
                :style="{ left: (isMuted ? 0 : volume * 100) + '%' }"
                :class="{ 'dragging': isVolumeDragging }"></div>
        </div>
            <div 
              v-if="showVolumeTooltip" 
              class="volume-tooltip"
              :style="{ left: volumeTooltipPosition + 'px' }">
              {{ Math.round((isMuted ? 0 : volume) * 100) }}%
            </div>
          </div>
        </div>

        <button class="control-btn" title="全屏">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M5.828 10.172a.5.5 0 0 0-.707 0l-4.096 4.096V11a.5.5 0 0 0-1 0v3.975a.5.5 0 0 0 .5.5H4.5a.5.5 0 0 0 0-1H1.232l4.096-4.096a.5.5 0 0 0 0-.707zm4.344 0a.5.5 0 0 1 .707 0l4.096 4.096V11a.5.5 0 1 1 1 0v3.975a.5.5 0 0 1-.5.5H11.5a.5.5 0 0 1 0-1h3.268l-4.096-4.096a.5.5 0 0 1 0-.707z"/>
            <path d="M10.172 5.828a.5.5 0 0 0 0-.707l4.096-4.096V4a.5.5 0 1 0 1 0V.025a.5.5 0 0 0-.5-.5H11.5a.5.5 0 0 0 0 1h3.268l-4.096 4.096a.5.5 0 0 0 0 .707zM5.828 5.828a.5.5 0 0 1 0-.707L1.732 1.025H5a.5.5 0 0 1 0-1H.025a.5.5 0 0 1-.5-.5V4a.5.5 0 0 1 1 0V1.732l4.096 4.096a.5.5 0 0 1 .707 0z"/>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import externalAudioService from '@/utils/externalAudioService'

export default {
  name: 'MusicPlayer',
  
  computed: {
    ...mapState('player', [
      'currentMusic',
      'isPlaying', 
      'currentTime',
      'duration',
      'volume',
      'isMuted',
      'showPlayer',
      'playMode',
      'isShuffle'
    ]),
    
    ...mapGetters('player', [
      'formattedCurrentTime',
      'formattedDuration', 
      'progress',
      'hasPrevious',
      'hasNext',
      'isCurrentMusicFavorited'
    ]),
    
    // 检查当前音乐是否为外部URL
    isExternalMusic() {
      if (!this.currentMusic || !this.currentMusic.filePath) return false
      return externalAudioService.isExternalUrl(this.currentMusic.filePath)
    },

    // 获取重复播放模式的标题
    getRepeatTitle() {
      switch (this.playMode) {
        case 'repeat-all': return '重复播放列表'
        case 'repeat-one': return '重复当前歌曲'
        default: return '重复播放'
      }
    }
  },
  
  watch: {
    currentMusic(newMusic, oldMusic) {
      console.log('当前音乐变化:', { newMusic: newMusic?.title, oldMusic: oldMusic?.title })
      
      if (newMusic && newMusic !== oldMusic) {
        this.loadMusic()
      } else if (!newMusic) {
        if (this.$refs.audio) {
          this.$refs.audio.src = ''
        }
      }
    },
    
    isPlaying(newVal) {
      console.log('播放状态变化:', newVal)
      
      if (newVal) {
        this.startPlayback()
      } else {
        this.pausePlayback()
      }
    },
    
    volume(newVal) {
      if (this.$refs.audio) {
        this.$refs.audio.volume = this.isMuted ? 0 : newVal
      }
    },
    
    isMuted(newVal) {
      if (this.$refs.audio) {
        this.$refs.audio.volume = newVal ? 0 : this.volume
      }
    },
    
    // 监听当前音乐变化
    async 'currentMusic.filePath'(newPath, oldPath) {
      console.log('当前音乐文件路径变化:', { newPath, oldPath })
      
      if (newPath && newPath !== oldPath) {
        this.isLoading = true
        await this.loadMusic()
      } else if (!newPath) {
        // 清理音频
        if (this.$refs.audio) {
          this.$refs.audio.src = ''
        }
      }
    }
  },
  
  async mounted() {
    // 设置音量
    if (this.$refs.audio) {
      this.$refs.audio.volume = this.volume
      
      // 设置音频属性以防止自动暂停
      this.$refs.audio.setAttribute('preload', 'metadata')
      this.$refs.audio.setAttribute('data-keep-playing', 'true')
      
      // 监听浏览器尝试暂停音频的事件
      this.$refs.audio.addEventListener('suspend', (event) => {
        console.log('浏览器尝试暂停音频，阻止暂停')
        if (this.isPlaying && document.hidden) {
          event.preventDefault()
          setTimeout(() => {
            if (this.$refs.audio && this.isPlaying) {
              this.$refs.audio.play().catch(error => {
                console.warn('阻止暂停后恢复播放失败:', error)
              })
            }
          }, 100)
        }
      })
    }
    
    console.log('🎵 Spotify风格播放器已准备就绪')
    
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
    
    // 添加页面可见性变化监听
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
    
    // 添加窗口焦点事件监听
    window.addEventListener('focus', this.handleWindowFocus)
    window.addEventListener('blur', this.handleWindowBlur)
    
    // 添加全局鼠标事件监听
    document.addEventListener('mousemove', this.onGlobalMouseMove)
    document.addEventListener('mouseup', this.onGlobalMouseUp)
  },
  
  beforeUnmount() {
    // 组件销毁时暂停音频并清理Blob URL
    if (this.$refs.audio) {
      this.$refs.audio.pause()
      this.$refs.audio.src = ''
    }
    
    // 清理Blob URL
    if (this.currentBlobUrl) {
      URL.revokeObjectURL(this.currentBlobUrl)
      this.currentBlobUrl = null
    }
  },
  
  beforeDestroy() {
    // 清理事件监听器
    document.removeEventListener('visibilitychange', this.handleVisibilityChange)
    window.removeEventListener('focus', this.handleWindowFocus)
    window.removeEventListener('blur', this.handleWindowBlur)
    document.removeEventListener('mousemove', this.onGlobalMouseMove)
    document.removeEventListener('mouseup', this.onGlobalMouseUp)
  },
  
  data() {
    return {
      isLoading: false,
      isPendingPlay: false,
      
      // 进度条拖拽相关
      isDragging: false,
      showProgressTooltip: false,
      tooltipPosition: 0,
      tooltipTime: '0:00',
      
      // 音量条拖拽相关
      isVolumeDragging: false,
      showVolumeTooltip: false,
      volumeTooltipPosition: 0,
      
      // 音频状态缓存
      cachedProgress: 0,
      
      // 用于优化性能的防抖
      progressUpdateTimer: null
    }
  },
  
  methods: {
    ...mapActions('player', [
      'togglePlay',
      'seek', 
      'setVolume',
      'toggleMute',
      'previous',
      'next',
      'updateTime',
      'toggleFavorite'
    ]),
    
    // 处理收藏按钮点击
    async handleToggleFavorite() {
      if (!this.currentMusic) {
        console.warn('没有当前播放的音乐')
        return
      }
      
      console.log('收藏按钮点击，当前音乐:', this.currentMusic)
      console.log('当前收藏状态:', this.isCurrentMusicFavorited)
      console.log('收藏列表:', this.$store.getters['player/favorites'])
      
      await this.toggleFavorite(this.currentMusic)
      
      // 等待一下再检查状态
      setTimeout(() => {
        console.log('收藏操作后状态:', this.isCurrentMusicFavorited)
      }, 100)
    },
    
    // 切换随机播放
    toggleShuffle() {
      this.$store.commit('player/SET_SHUFFLE', !this.isShuffle)
    },
    
    // 切换重复播放模式
    toggleRepeat() {
      const modes = ['normal', 'repeat-all', 'repeat-one']
      const currentIndex = modes.indexOf(this.playMode)
      const nextMode = modes[(currentIndex + 1) % modes.length]
      this.$store.commit('player/SET_PLAY_MODE', nextMode)
    },

    // 加载音乐
    async loadMusic() {
      if (!this.currentMusic || !this.$refs.audio || this.isLoading) {
        return
      }
      
      console.log('🎵 开始加载音乐:', this.currentMusic.title)
      
      // 暂停当前播放，避免冲突
      this.$refs.audio.pause()
      this.isLoading = true
      
      try {
        // 处理文件路径，提取文件名并构建正确的HTTP URL
        let musicUrl = this.currentMusic.src || this.currentMusic.filePath
        
        // 检查是否有有效的音频源
        if (!musicUrl) {
          console.error('❌ 音乐文件路径为空，无法播放:', this.currentMusic)
          this.$store.commit('player/SET_PLAYING', false)
          this.isLoading = false
          return
        }
        
        let fullUrl
        
        // 检查是否为外部音乐URL
        if (externalAudioService.isExternalUrl(musicUrl)) {
          console.log('🌐 检测到外部音乐URL:', musicUrl)
          fullUrl = musicUrl
          
          // 为外部URL设置特殊的音频属性
          this.$refs.audio.crossOrigin = 'anonymous'
          this.$refs.audio.preload = 'metadata'
        } else if (musicUrl.startsWith('http://') || musicUrl.startsWith('https://')) {
          // 其他完整的HTTP URL，直接使用
          console.log('🔗 检测到完整HTTP URL:', musicUrl)
          fullUrl = musicUrl
          
          // 为其他HTTP URL设置音频属性
          this.$refs.audio.crossOrigin = 'anonymous'
          this.$refs.audio.preload = 'metadata'
        } else {
          // 本地文件处理
          console.log('🏠 处理本地文件路径:', musicUrl)
          if (musicUrl.includes('/uploads/songs/')) {
            const fileName = musicUrl.split('/').pop()
            musicUrl = `/api/files/songs/${fileName}`
          } else if (!musicUrl.startsWith('/api/')) {
            // 如果不是API路径，假设是文件名
            const fileName = musicUrl.split('/').pop()
            musicUrl = `/api/files/songs/${fileName}`
          }
          
          fullUrl = `http://localhost:2025${musicUrl}`
          
          // 为本地文件设置音频属性
          this.$refs.audio.crossOrigin = 'use-credentials'
          this.$refs.audio.preload = 'auto'
        }
        
        console.log('🔗 准备设置音频源:', fullUrl)
        
        // 使用外部音频服务设置音频源
        if (externalAudioService.isExternalUrl(fullUrl)) {
          console.log('🌐 使用外部音频服务处理URL')
          await externalAudioService.setAudioSource(this.$refs.audio, fullUrl)
          
          // 确保音频源已设置
          if (this.$refs.audio.src) {
            console.log('✅ 外部音频源设置完成:', this.$refs.audio.src)
          } else {
            console.error('❌ 外部音频源设置失败')
          }
        } else {
          // 直接设置本地音频源
          console.log('🔗 设置本地音频源:', fullUrl)
          this.$refs.audio.src = fullUrl
        }
        
        // 开始加载
        this.$refs.audio.load()
        
        // 设置20秒超时处理
        setTimeout(() => {
          if (this.isLoading) {
            console.warn('⚠️ 音频加载超时，但不强制停止，继续等待...')
          }
        }, 20000)
        
      } catch (error) {
        console.error('❌ 设置音频源失败:', error)
        this.$store.commit('player/SET_PLAYING', false)
        this.isLoading = false
      }
    },
    
    // 处理播放点击
    handlePlayClick() {
      console.log('🎯 用户点击播放按钮')
      
      if (!this.currentMusic) {
        console.warn('⚠️ 没有选择音乐')
        return
      }
      
      // 如果正在加载，忽略点击
      if (this.isLoading) {
        console.log('⏳ 正在加载音乐，忽略点击')
        return
      }
      
      // 如果没有音频源，先加载音乐
      if (!this.$refs.audio.src) {
        console.log('🔄 没有音频源，先加载音乐')
        this.loadMusic()
        return
      }
      
      // 切换播放状态
      this.$store.commit('player/SET_PLAYING', !this.isPlaying)
    },
    
    // 开始播放
    async startPlayback() {
      console.log('🎬 尝试开始播放音频...')
      
      if (!this.$refs.audio) {
        console.error('❌ 音频元素不存在')
        return
      }
      
      // 检查音频源
      if (!this.$refs.audio.src) {
        console.log('⏳ 音频源为空，等待异步设置完成...')
        
        // 等待最多3秒
        let attempts = 0
        const maxAttempts = 6
        
        while (!this.$refs.audio.src && attempts < maxAttempts) {
          await new Promise(resolve => setTimeout(resolve, 500))
          attempts++
          console.log(`⌛ 等待音频源设置 (${attempts}/${maxAttempts})`)
        }
        
        if (!this.$refs.audio.src) {
          console.warn('⚠️ 等待超时，音频源仍为空，尝试重新加载音乐')
          this.loadMusic()
          return
        }
      }
      
      try {
        console.log('🎵 执行播放命令...')
        const playPromise = this.$refs.audio.play()
        
        if (playPromise !== undefined) {
          await playPromise
          console.log('✅ 音频播放成功启动')
          
          // 确保Vuex状态同步
          if (!this.isPlaying) {
            this.$store.commit('player/SET_PLAYING', true)
          }
        }
      } catch (error) {
        console.error('❌ 播放失败:', error)
        this.$store.commit('player/SET_PLAYING', false)
        this.isLoading = false
      }
    },
    
    // 暂停播放
    pausePlayback() {
      if (this.$refs.audio) {
        console.log('暂停音频播放')
        this.$refs.audio.pause()
      }
    },

    // 获取封面URL
    getCoverUrl(coverPath) {
      if (!coverPath) return null
      
      // 如果已经是完整的HTTP URL，直接使用
      if (coverPath.startsWith('http://') || coverPath.startsWith('https://')) {
        return coverPath
      }
      
      // 构建完整URL
      const baseUrl = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080'
      
      // 如果是相对路径，直接拼接
      if (coverPath.startsWith('/')) {
        return `${baseUrl}${coverPath}`
      }
      
      // 如果是文件名，假设在uploads目录
      return `${baseUrl}/uploads/covers/${coverPath}`
    },
    
    // 进度条拖拽处理
    onProgressMouseDown(event) {
      if (!this.$refs.audio || this.duration <= 0) return
      
      this.isDragging = true
      event.preventDefault()
      
      // 立即设置时间
      this.updateProgressFromMouse(event)
    },
    
    onProgressMouseMove(event) {
      // 显示提示框
      if (this.$refs.progressContainer && !this.isDragging) {
        const rect = this.$refs.progressContainer.getBoundingClientRect()
        const percent = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width))
        const time = percent * this.duration
        
        this.showProgressTooltip = true
        this.tooltipPosition = event.clientX - rect.left
        this.tooltipTime = this.formatTime(time)
      }
      
      if (this.isDragging) {
        this.updateProgressFromMouse(event)
      }
    },
    
    hideProgressTooltip() {
      this.showProgressTooltip = false
    },
    
    updateProgressFromMouse(event) {
      if (!this.$refs.progressContainer || !this.$refs.audio || this.duration <= 0) return
      
      const rect = this.$refs.progressContainer.getBoundingClientRect()
      const percent = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width))
      const time = percent * this.duration
      
      // 直接设置音频时间
      this.$refs.audio.currentTime = time
      // 同步到store
      this.$store.commit('player/SET_CURRENT_TIME', time)
    },

    // 音量条拖拽处理
    onVolumeMouseDown(event) {
      this.isVolumeDragging = true
      event.preventDefault()
      
      this.updateVolumeFromMouse(event)
    },
    
    onVolumeMouseMove(event) {
      // 显示提示框
      if (this.$refs.volumeContainer && !this.isVolumeDragging) {
        const rect = this.$refs.volumeContainer.getBoundingClientRect()
        this.showVolumeTooltip = true
        this.volumeTooltipPosition = event.clientX - rect.left
      }
      
      if (this.isVolumeDragging) {
        this.updateVolumeFromMouse(event)
      }
    },
    
    hideVolumeTooltip() {
      this.showVolumeTooltip = false
    },
    
    updateVolumeFromMouse(event) {
      if (!this.$refs.volumeContainer) return
      
      const rect = this.$refs.volumeContainer.getBoundingClientRect()
      const percent = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width))
      
      this.setVolume(percent)
      
      if (this.isMuted && percent > 0) {
        this.toggleMute()
      }
    },

    // 全局鼠标事件处理
    onGlobalMouseMove(event) {
      if (this.isDragging) {
        this.updateProgressFromMouse(event)
      }
      if (this.isVolumeDragging) {
        this.updateVolumeFromMouse(event)
      }
    },
    
    onGlobalMouseUp() {
      this.isDragging = false
      this.isVolumeDragging = false
    },

    // 格式化时间
    formatTime(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || isNaN(seconds) || seconds < 0) {
        return '0:00'
      }
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    },

    // 音频事件处理器
    onLoadStart() {
      console.log('音频开始加载')
    },
    
    onLoadedMetadata() {
      if (this.$refs.audio) {
        console.log('音频元数据加载完成:', {
          duration: this.$refs.audio.duration,
          src: this.$refs.audio.src,
          readyState: this.$refs.audio.readyState
        })
        this.$store.commit('player/SET_DURATION', this.$refs.audio.duration)
      }
    },
    
    onCanPlay() {
      console.log('音频可以播放')
      this.isLoading = false
      
      // 如果当前状态是播放中，立即开始播放
      if (this.isPlaying) {
        console.log('🎬 当前状态为播放中，立即开始播放')
        this.startPlayback()
      }
    },
    
    onTimeUpdate() {
      if (this.$refs.audio && !this.isDragging) {
        const currentTime = this.$refs.audio.currentTime
        this.$store.commit('player/SET_CURRENT_TIME', currentTime)
      }
    },
    
    onPlay() {
      console.log('音频开始播放')
          // 确保Vuex状态同步
          if (!this.isPlaying) {
            this.$store.commit('player/SET_PLAYING', true)
          }
    },
    
    onPause() {
      console.log('音频暂停事件触发')
      
      // 如果页面隐藏且我们希望继续播放，则尝试恢复播放
      if (document.hidden && this.isPlaying) {
        console.log('检测到页面失焦导致的暂停，尝试恢复播放...')
        
          setTimeout(() => {
          if (this.$refs.audio && this.isPlaying && document.hidden) {
            console.log('恢复后台播放')
            this.$refs.audio.play().catch(error => {
              console.warn('后台恢复播放失败:', error)
            })
          }
        }, 100)
        
        return // 不更新Vuex状态，保持播放状态
      }
      
      // 正常的暂停情况，更新状态
      console.log('正常音频暂停')
      if (this.isPlaying) {
        this.$store.commit('player/SET_PLAYING', false)
      }
    },
    
    onEnded() {
      console.log('音频播放结束')
      this.$store.dispatch('player/onEnded')
    },
    
    onWaiting() {
      console.log('音频缓冲中')
    },
    
    onStalled() {
      console.log('音频加载停滞')
    },
    
    onError(error) {
      console.error('音乐播放错误:', error)
        this.$store.commit('player/SET_PLAYING', false)
      this.isLoading = false
    },

    // 页面可见性处理
    handleVisibilityChange() {
      console.log('页面可见性变化:', document.hidden ? '隐藏' : '显示')
      
      if (!document.hidden && this.isPlaying && this.$refs.audio) {
        // 页面重新获得焦点，且应该播放音乐时，确保音频正在播放
        setTimeout(() => {
          if (this.$refs.audio.paused && this.isPlaying) {
            console.log('页面重新获得焦点，恢复音频播放')
            this.$refs.audio.play().catch(error => {
              console.warn('恢复播放失败:', error)
            })
          }
        }, 200)
      }
    },

    handleWindowFocus() {
      console.log('窗口获得焦点')
      // 窗口获得焦点时，确保音频继续播放
      if (this.isPlaying && this.$refs.audio && this.$refs.audio.paused) {
        setTimeout(() => {
          this.$refs.audio.play().catch(error => {
            console.warn('窗口获得焦点时恢复播放失败:', error)
          })
        }, 100)
      }
    },

    handleWindowBlur() {
      console.log('窗口失去焦点')
      // 窗口失去焦点时不做任何操作，让音频继续播放
    }
  }
}
</script>

<style scoped>
/* Spotify风格的播放器样式 */
.spotify-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 90px;
  background: #181818;
  border-top: 1px solid #282828;
  z-index: 1000;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  transition: all 0.3s ease;
}

.player-container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  background-color: #000000;
  height: 100%;
  align-items: center;
  padding: 0 16px;
  gap: 16px;
  transition: all 0.3s ease;
}

/* 左侧：当前播放信息 */
.now-playing {
  display: flex;
  align-items: center;
  min-width: 0;
  flex: 1;
  transition: all 0.3s ease;
}

.track-info {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
  flex: 1;
  transition: all 0.3s ease;
}

.track-image {
  width: 56px;
  height: 56px;
  border-radius: 4px;
  overflow: hidden;
  background: #282828;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.track-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.default-cover {
  color: #b3b3b3;
  font-size: 24px;
  transition: all 0.3s ease;
}

.track-details {
  min-width: 0;
  flex: 1;
  transition: all 0.3s ease;
}

.track-name {
  color: white;
  font-size: 14px;
  font-weight: 400;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.track-name:hover {
  text-decoration: underline;
}

.track-artist {
  color: #b3b3b3;
  font-size: 11px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  transition: all 0.3s ease;
}

.track-artist:hover {
  color: white;
  text-decoration: underline;
}

.external-badge {
  margin-left: 6px;
  font-size: 10px;
  transition: all 0.3s ease;
}

/* 中央：播放控制 */
.player-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  max-width: 722px;
  width: 100%;
  transition: all 0.3s ease;
}

.control-buttons {
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.control-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.control-btn:hover:not(:disabled) {
  color: white;
  transform: scale(1.06);
}

.control-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.control-btn.active {
  color: #1db954 !important;
}

.heart-btn.active {
  color: #1db954 !important;
}

.heart-btn.active svg {
  color: #1db954 !important;
}

.play-pause-btn {
  background: white;
  color: #000;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  margin: 0 8px;
}

.play-pause-btn:hover:not(:disabled) {
  transform: scale(1.1);
  background: #f7f7f7;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

.play-pause-btn:active:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
}

.play-pause-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.loading-spinner {
  animation: spin 1s linear infinite;
  transition: all 0.3s ease;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 进度条样式 */
.progress-section {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  transition: all 0.3s ease;
}

.time-display {
  color: #b3b3b3;
  font-size: 11px;
  font-weight: 400;
  min-width: 40px;
  text-align: center;
  font-variant-numeric: tabular-nums;
  transition: all 0.3s ease;
}

.progress-bar-container {
  flex: 1;
  position: relative;
  height: 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.progress-bar {
  width: 100%;
  height: 4px;
  position: relative;
  background: transparent;
  transition: all 0.3s ease;
}

.progress-background {
  width: 100%;
  height: 100%;
  background: #5e5e5e;
  border-radius: 2px;
  transition: all 0.3s ease;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: #1db954;
  border-radius: 2px;
  transition: none;
  transition: all 0.3s ease;
}

.progress-handle {
  position: absolute;
  top: 50%;
  transform: translateY(-50%) translateX(-50%);
  width: 12px;
  height: 12px;
  background: white;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.2s ease;
  cursor: grab;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  transition: all 0.3s ease;
}

.progress-bar-container:hover .progress-background {
  background: #fff;
}

.progress-bar-container:hover .progress-handle {
  opacity: 1;
}

.progress-handle.dragging {
  opacity: 1;
  cursor: grabbing;
  transform: translateY(-50%) translateX(-50%) scale(1.2);
  transition: all 0.3s ease;
}

.progress-tooltip {
  position: absolute;
  bottom: 20px;
  background: #282828;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  white-space: nowrap;
  pointer-events: none;
  z-index: 1001;
  transform: translateX(-50%);
  transition: all 0.3s ease;
}

/* 右侧：其他控制 */
.extra-controls {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  min-width: 0;
  transition: all 0.3s ease;
}

.volume-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.volume-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.volume-btn:hover {
  color: white;
  transform: scale(1.06);
}

.heart-btn.active {
  color: #1db954;
}

.heart-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.volume-bar-container {
  width: 100px;
  height: 12px;
  position: relative;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.volume-bar {
  width: 100%;
  height: 4px;
  position: relative;
  background: transparent;
  transition: all 0.3s ease;
}

.volume-background {
  width: 100%;
  height: 100%;
  background: #5e5e5e;
  border-radius: 2px;
  transition: all 0.3s ease;
}

.volume-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: #1db954;
  border-radius: 2px;
  transition: none;
  transition: all 0.3s ease;
}

.volume-handle {
  position: absolute;
  top: 50%;
  transform: translateY(-50%) translateX(-50%);
  width: 12px;
  height: 12px;
  background: white;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.2s ease;
  cursor: grab;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  transition: all 0.3s ease;
}

.volume-bar-container:hover .volume-background {
  background: #fff;
}

.volume-bar-container:hover .volume-handle {
  opacity: 1;
}

.volume-handle.dragging {
  opacity: 1;
  cursor: grabbing;
  transform: translateY(-50%) translateX(-50%) scale(1.2);
}

.volume-tooltip {
  position: absolute;
  bottom: 20px;
  background: #282828;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  white-space: nowrap;
  pointer-events: none;
  z-index: 1001;
  transform: translateX(-50%);
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .player-container {
    grid-template-columns: 1fr auto 1fr;
    gap: 8px;
    padding: 0 8px;
  }
  
  .track-info {
    gap: 8px;
  }
  
  .track-image {
    width: 40px;
    height: 40px;
  }
  
  .control-buttons {
    gap: 12px;
  }
  
  .extra-controls {
    gap: 4px;
  }
  
  .volume-bar-container {
    width: 60px;
  }
  
  .time-display {
    font-size: 10px;
    min-width: 35px;
  }
}

/* 防止用户选择和拖拽 */
.spotify-player * {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -webkit-touch-callout: none;
}

.spotify-player audio {
  display: none !important;
  visibility: hidden !important;
}

.spotify-player img {
  -webkit-user-drag: none;
  -khtml-user-drag: none;
  -moz-user-drag: none;
  -o-user-drag: none;
  user-drag: none;
  pointer-events: none;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 12px;
}

::-webkit-scrollbar-track {
  background: #000;
}

::-webkit-scrollbar-thumb {
  background: #333;
  border-radius: 6px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style> 